package com.abel.repository.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.abel.datamodel.type.WorkHistory;
import com.abel.domain.WorkExperience;
import com.abel.domain.PersonSearchCriteria;
import com.abel.repository.WorkExperienceRepository;
import com.abel.repository.exception.RepositoryException;
import com.abel.util.UserSessionLocator;

public class WorkExperienceRepositoryImpl extends BaseRepositoryImpl implements WorkExperienceRepository {

	/**
	 * @author BG
	 *
	 */

	    protected final Log logger = LogFactory.getLog(getClass());

	    /* (non-Javadoc)
		 * @see com.abel.repository.WorkExperienceRepository#addWorkExperience(com.abel.domain.WorkExperience)
		 */
		@Override
		public int addWorkExperience(WorkExperience workExperience) throws RepositoryException 
		{
		    logger.debug("@WorkExperienceRepositoryimpl : addWorkExperience : entered");
		
		    Transaction tx = null;
			Session session = null;
			WorkHistory workHistory = new WorkHistory();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//add an WorkExperience record
				workHistory.setAplId(workExperience.getAplId());
				workHistory.setWrkStartDate(workExperience.getWrkStartDate());
				workHistory.setWrkEndDate(workExperience.getWrkEndDate());
				workHistory.setWrkCompanyName(workExperience.getWrkCompanyName());
				workHistory.setWrkAddrLine1(workExperience.getWrkAddrLine1());
				workHistory.setWrkAddrLine2(workExperience.getWrkAddrLine2());
				workHistory.setWrkCity(workExperience.getWrkCity());
				workHistory.setWrkState(workExperience.getWrkState());
				workHistory.setWrkZip(workExperience.getWrkZip());
				workHistory.setWrkBusinessType(workExperience.getWrkBusinessType());
				workHistory.setWrkPosition(workExperience.getWrkPosition());
				workHistory.setWrkSupervisorName(workExperience.getWrkSupervisorName());
				workHistory.setWrkGrossHourlyPay(workExperience.getWrkGrossHourlyPay());
				workHistory.setWrkGrossAnnualPay(workExperience.getWrkGrossAnnualPay());
				workHistory.setWrkLeaveReason(workExperience.getWrkLeaveReason());
				workHistory.setWrkResponsibility(workExperience.getWrkResponsibility());
				workHistory.setWrkCreateDts(new java.sql.Timestamp(System.currentTimeMillis()));

		
				//saving data to table
				int wrkHistId = Integer.parseInt(((Object)session.save(workHistory)).toString());
				tx.commit();
				
				return wrkHistId;
		
		} 
		catch (RuntimeException e) {
			//TODO check for duplicate key exception and throw it
			/*
			logger.info("@ : addRegistration : exception - more than one user record found for user name = " + usrs.getUserName());
			throw new RepositoryException("More than one user record found for user name = " + usrs.getUserName());
			 */
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
				
					tx.rollback();
				
				} 
				catch (HibernateException he) {
					logger.debug("@WorkExperienceRepositoryImpl : addWorkExperience : exception while rolling back WorkExperience" + he);
					he.printStackTrace();
				}
			}
			throw new RepositoryException("Exception while adding WorkExperience.",e);
		}

	}


		/* (non-Javadoc)
		 * @see com.abel.repository.WorkExperienceRepository#updateWorkExperience(com.abel.domain.WorkExperience)
		 */
		@Override
		public void updateWorkExperience(WorkExperience workExperience) throws RepositoryException {
		    logger.debug("@WorkExperienceRepositoryimpl : deleteWorkExperience : entered");
			
		    Transaction tx = null;
			Session session = null;
			WorkHistory workHistory = new WorkHistory();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//update WorkExperience record
				workHistory.setWrkHistId(workExperience.getWrkHistId());
				workHistory.setAplId(workExperience.getAplId());
				workHistory.setWrkStartDate(workExperience.getWrkStartDate());
				workHistory.setWrkEndDate(workExperience.getWrkEndDate());
				workHistory.setWrkCompanyName(workExperience.getWrkCompanyName());
				workHistory.setWrkAddrLine1(workExperience.getWrkAddrLine1());
				workHistory.setWrkAddrLine2(workExperience.getWrkAddrLine2());
				workHistory.setWrkCity(workExperience.getWrkCity());
				workHistory.setWrkState(workExperience.getWrkState());
				workHistory.setWrkZip(workExperience.getWrkZip());
				workHistory.setWrkBusinessType(workExperience.getWrkBusinessType());
				workHistory.setWrkPosition(workExperience.getWrkPosition());
				workHistory.setWrkSupervisorName(workExperience.getWrkSupervisorName());
				workHistory.setWrkGrossHourlyPay(workExperience.getWrkGrossHourlyPay());
				workHistory.setWrkGrossAnnualPay(workExperience.getWrkGrossAnnualPay());
				workHistory.setWrkLeaveReason(workExperience.getWrkLeaveReason());
				workHistory.setWrkResponsibility(workExperience.getWrkResponsibility());
				workHistory.setWrkCreateDts(workExperience.getWrkCreateDts());
				workHistory.setWrkLastUpdateDts(new java.sql.Timestamp(System.currentTimeMillis()));
				workHistory.setWrkLastUpdateId(UserSessionLocator.getUserSession().getAuthPrincipal().getUserName());
			
				//getting userId from UserSession
				int userId = UserSessionLocator.getUserSession().getAuthPrincipal().getUserId();
				if (userId <= 0) {
					throw new RepositoryException("Cannot update WorkExperience information. UserId in authPrincipal is " + userId);
				}
		
				//updating WorkExperience information
				session.update(workHistory);
				tx.commit();
				
		} 
		catch (RuntimeException e) {
			//TODO check for duplicate key exception and throw it
			/*
			logger.info("@ : addRegistration : exception - more than one user record found for user name = " + usrs.getUserName());
			throw new RepositoryException("More than one user record found for user name = " + usrs.getUserName());
			 */
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
						tx.rollback();
					} 
					catch (HibernateException he) {
						logger.debug("@WorkExperienceRepositoryImpl : updateWorkExperience : exception while rolling back WorkExperience" + he);
						he.printStackTrace();
					}
				}
				throw new RepositoryException("Exception while updating WorkExperience.",e);
			}
		}

		/* (non-Javadoc)
		 * @see com.abel.repository.WorkExperienceRepository#deleteWorkExperience(com.abel.domain.WorkExperience)
		 */
		@Override
		public void deleteWorkExperience(int aplId, int wrkHistId) throws RepositoryException {
		    logger.debug("@WorkExperienceRepositoryimpl : deleteWorkExperience : entered");
			
		    Transaction tx = null;
			Session session = null;
			WorkHistory workHistory = new WorkHistory();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//delete WorkExperience record
				workHistory.setWrkHistId(wrkHistId);
				workHistory.setAplId(aplId);

				session.delete(workHistory);
				tx.commit();
				
		} 
		catch (RuntimeException e) {
			//TODO check for duplicate key exception and throw it
			logger.info("@ : deleteWorkHistory : exception - delete failed for WorkHistory.wrk_Hist_id= " + wrkHistId);
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
						tx.rollback();
					} 
					catch (HibernateException he) {
						logger.debug("@WorkExperienceRepositoryImpl : deleteWorkExperience : exception while rolling back WorkExperience" + he);
						he.printStackTrace();
					}
				}
				throw new RepositoryException("Exception while deleteing WorkExperience.",e);
			}
		}

		/* (non-Javadoc)
		 * @see com.abel.repository.WorkExperienceRepository#deleteWorkExperience(com.abel.domain.WorkExperience)
		 */
		@Override
		public void deleteWorkExperience(int wrkHistId) throws RepositoryException {
		    logger.debug("@WorkExperienceRepositoryimpl : deleteWorkExperience : entered");
			
		    Transaction tx = null;
			Session session = null;
			WorkHistory workHistory = new WorkHistory();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//delete WorkExperience record
				workHistory.setWrkHistId(wrkHistId);

				session.delete(workHistory);
				tx.commit();
				
		} 
		catch (RuntimeException e) {
			//TODO check for duplicate key exception and throw it
			logger.info("@ : deleteWorkHistory : exception - delete failed for WorkHistory.wrk_hist_id= " + wrkHistId);
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
						tx.rollback();
					} 
					catch (HibernateException he) {
						logger.debug("@WorkExperienceRepositoryImpl : deleteWorkExperience : exception while rolling back WorkExperience" + he);
						he.printStackTrace();
					}
				}
				throw new RepositoryException("Exception while deleteing WorkExperience.",e);
			}
		}

		/* (non-Javadoc)
		 * @see com.abel.repository.WorkExperienceRepository#deleteWorkExperience(com.abel.domain.WorkExperience)
		 */
		@Override
		public void deleteWorkExperience(WorkExperience workExperience) throws RepositoryException {
		    logger.debug("@WorkExperienceRepositoryimpl : deleteWorkExperience : entered");
			
		    Transaction tx = null;
			Session session = null;
			WorkHistory workHistory = new WorkHistory();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//delete WorkExperience record
				workHistory.setWrkHistId(workExperience.getWrkHistId());

				session.delete(workHistory);
				tx.commit();
				
		} 
		catch (RuntimeException e) {
			//TODO check for duplicate key exception and throw it
			logger.info("@ : deleteWorkHistory : exception - delete failed for WorkExperiences.wrk_hist_id= " + workExperience.getWrkHistId());
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
						tx.rollback();
					} 
					catch (HibernateException he) {
						logger.debug("@WorkExperienceRepositoryImpl : deleteWorkExperience : exception while rolling back WorkExperience" + he);
						he.printStackTrace();
					}
				}
				throw new RepositoryException("Exception while deleteing WorkExperience.",e);
			}
		}

		/* (non-Javadoc)
		 * @see com.abel.repository.WorkExperienceRepository#getWorkExperienceInformation(com.abel.domain.PersonSearchCriteria)
		 */
		@Override
		public List<WorkExperience> getWorkExperience(PersonSearchCriteria criteria)
				throws RepositoryException {
			// TODO Auto-generated method stub

		Transaction tx = null;
		Session session = null;

		try {
			session = this.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();
			
			List<WorkExperience> workList = session.getNamedQuery("getWorkExperienceByUser").
			setParameter("userId", criteria.getUserId()).list();  
			// TODO how to get the apl_id - ask joseph to implement

			tx.commit();
			return workList;
		} 
		catch (RuntimeException e) {
			
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
				
					tx.rollback();
				
				}
				catch (HibernateException he) {
				
					logger.debug("@AuthRepositoryImpl : addRegistration : exception while rolling back registration" + he);
					he.printStackTrace();
				
				}
			}
			throw new RepositoryException("Excpetion while getting WorkExperience for user Id=" + criteria.getUserId(),e);
		}
		}
}
